var req;
var words;
var catalogue;
var questionLang;
var answerLang;
var langsDirection = 0;
var response;
var directionTexts = new Array("English to Japanese (英語から日本語)", 
							   "Japanese to English (日本語から英語)");
var answerText = new Array("Candidate (候補)", "Wrong Answer (不正解)");
var answerID = new Array("answer0", "answer1", "answer2");
var filename;
var mode;
var score;
function init() {
    // english, class number, japanese
    words = new Array();
    // adjective, adverb, noun, verb
    catalogue = new Array(new Array(), new Array(), new Array(), new Array());
    response = null;
    if (langsDirection == 0) {
        questionLang = 0;
        answerLang = 2;
    } else {
        questionLang = 2;
        answerLang = 0;
    }
    $("direction").value = directionTexts[0];
	score = new Array(100);
	for (var i=0; i<score.length; i++) {
		score[i] = 0;
	}
}

function loadTabbedData(obj) {
    $("loading").innerHTML = "now loading...";
    init();
    if (obj == null) {
        filename = getSelectedRadio(document.settings.level).value;
    } else {
        filename = obj.value;
	} 
	displayScore();
	
    new Ajax.Request(filename, {
        method: 'get',
        onSuccess: function (transport) {
            response = transport.responseText;
            importTabbedData();
            nextQuestion();
            $("loading").innerHTML = "... has been loaded. <br>" +
				catalogue[0].length + " Adjectives, " +
				catalogue[1].length + " Adverbes, " +
				catalogue[2].length + " Nouns, " +
				catalogue[3].length + " Verbs.";
		},
		onFailuer: function () {
            $("loading").innerHTML = "... couldn't be loaded.";
		}
    });
}

function displayScore() {
	var sum = 0;
	for (var i=0; i<score.length; i++) {
		sum += score[i];
	}
	$('score').innerHTML = 100 * sum / score.length;
}

function renewScore(ans) {
	score.shift();
	score.push(ans);
}

function importTabbedData() {
    var lines = response.split("\r\n");
    for (var i=0; i < 2000; i++) {
        var cols = lines[i].split("\t");
        if (cols.length < 4) {
            continue;
        }
        var classNum = getClassNum(cols[2]);
        var wordId = "" + i;
        words[wordId] = Array(cols[1], classNum, cols[3]);
        var currClass = catalogue[classNum];
        currClass[currClass.length] = wordId;
    }
}

function getClassNum(type) {
    var res;
    if (type == "a") {
        res = 0;
    } else if (type == "ad") {
        res = 1;
    } else if (type == "n") {
        res = 2;
    } else if (type == "v") {
        res = 3;
    } else {
		alert("invalid type:" + type + " at getClassNum");
	}
    return res;
}

function getClassName(num) {
    var res;
    if (num == 0) {
        res = "Adjective (形容詞)";
    } else if (num == 1) {
        res = "Adverb (副詞)";
    } else if (num == 2) {
        res = "Noun (名詞)";
    } else if (num == 3) {
        res = "Verb (動詞)";
    } else {
		alert("invalid type:" + num + " at getClassName");
	}
    return res;
}

function getRandom(sup) {
    return "" + Math.floor(Math.random() * sup);
}

function setCandidates(num) {
    var i = 0;
    while (i < 3) {
        var dup = false;
        candidates[i] = catalogue[num][getRandom(catalogue[num].length)];
        for (var j=0; j<i; j++) {
            if (candidates[i] == candidates[j]) {
                dup = true;
                break;
            }
        }
        if (!dup) {
			// $(answerID[i]).value = words[candidates[i]][answerLang] + 
			//	" " + candidates[i];
			$(answerID[i]).value = words[candidates[i]][answerLang];
            i++;
        }
    }
}

var candidates;
var correctAnswer;
var answered;
var correctID;
function initQA() {
    candidates = new Array();
	correctAnswer = null;
	answered = 1;
}

function nextQuestion() {
    initQA();
    var questionType = words[getRandom(2000)][1];
    setCandidates(questionType);
    correctAnswer = getRandom(3);
    setQuestion();
}

function setQuestion() {
    correctID = candidates[correctAnswer];
    var correctWord = words[correctID];
    $("question").innerHTML = correctWord[questionLang];
    $("type").innerHTML = getClassName(correctWord[1]);
}    

function pushedAnswer(answer) {
    if (correctAnswer != answer) {
        $(answerID[answer]).value = answerText[1];
		answered = 0;
        return;
    }
	renewScore(answered);
	displayScore();
    nextQuestion();
}

function getSelectedRadio(radios) {
    var resnum = 0;
    for (var i=0; i < radios.length; i++) {
        if (radios[i].cheched) {
            resnum = i;
            break;
	    }
	}
	return radios[resnum];
}

function switchLangsDirection() {
    langsDirection++;    
    langsDirection %= 2;    
    $("direction").value = directionTexts[langsDirection];
    loadTabbedData(getSelectedRadio(document.settings.level));
}
